package com.eduadmin.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.eduadmin.entity.Teacher;
import com.eduadmin.exception.CustomException;
import com.eduadmin.service.ITeacherService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class TeacherDataUploadListener extends AnalysisEventListener<Teacher> {
    private int count = 1;         //解析excel文件的行数

    private final ITeacherService teacherService;

    public TeacherDataUploadListener(ITeacherService teacherService) {
        this.teacherService = teacherService;
    }

    List<Teacher> list = new ArrayList<>();
    private final List<String> errors = new ArrayList<>();   //记录数据重复的行数

    @Override
    public void invoke(Teacher data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        ++count;
        String teacherIdCard = data.getTeacherIdCard();
        if (teacherIdCard.length() == 18 && isCard(teacherIdCard)) {
            Teacher teacherByTeacherIdcard = teacherService.getTeacherByTeacherIdcard(teacherIdCard); //系统教师身份证号唯一
            //Teacher teacherByTeacherName = teacherService.getTeacherByTeacherName(data.getTeacherName()); //系统教师姓名唯一  重名的要加以区分 否则不能进入系统
            if (teacherByTeacherIdcard == null) {
                list.clear();
                list.add(data);
                saveData();
            } else {
                errors.add("Excel数据表中第 " + count + " 行 的身份证号已在系统中，不能导入！");
            }
        }else {
            errors.add("Excel数据表中第 " + count + " 行 的身份证号错误，不能导入！");
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有数据解析完成！");
        //抛自定义异常 如果有重复行
        if (errors.size() > 0) {
            throw new CustomException("/adminindex", "", errors);
        }
    }

    /**
     * 存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", count);
        if (!CollectionUtils.isEmpty(list)) {
            teacherService.addTeachers(list);
        }
        log.info("存储数据库成功！");
    }

    //18位身份证校验
    public boolean isCard(String id) {
        int[] w = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        char[] c = id.toCharArray();
        int sum = 0;
        for (int i = 0; i < w.length; i++) {
            sum += (c[i] - '0') * w[i];
        }
        char[] verifyCode = "10X98765432".toCharArray();
        char ch = verifyCode[sum % 11];
        return c[17] == ch;
    }
}
